using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using Book.Blog.Core.DTOs;
using Book.Blog.Core.Interfaces;

namespace Book.Blog.Infrastructure.Services
{
    public class LocalFileStorageService : IFileStorageService
    {
        private readonly IWebHostEnvironment _environment;
        private readonly IConfiguration _configuration;
        private readonly string _baseUrl;
        private readonly string _uploadPath;

        public LocalFileStorageService(IWebHostEnvironment environment, IConfiguration configuration)
        {
            _environment = environment;
            _configuration = configuration;
            _baseUrl = _configuration["FileStorage:BaseUrl"] ?? "http://localhost:5000";
            _uploadPath = Path.Combine(_environment.WebRootPath, "uploads");
            
            // 确保上传目录存在
            if (!Directory.Exists(_uploadPath))
            {
                Directory.CreateDirectory(_uploadPath);
            }
        }

        public async Task<FileUploadResultDTO> SaveFileAsync(Stream fileStream, string fileName, string contentType, FileUploadOptionsDTO? options = null)
        {
            options ??= new FileUploadOptionsDTO();
            var directory = options.Directory ?? "files";
            var directoryPath = Path.Combine(_uploadPath, directory);

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            // 生成唯一文件名
            var extension = Path.GetExtension(fileName);
            var uniqueFileName = $"{Guid.NewGuid()}{extension}";
            var filePath = Path.Combine(directoryPath, uniqueFileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await fileStream.CopyToAsync(stream);
            }

            return new FileUploadResultDTO
            {
                FileName = uniqueFileName,
                FileUrl = GetFileUrl(uniqueFileName, directory),
                FileSize = new FileInfo(filePath).Length,
                ContentType = contentType,
                UploadTime = DateTime.UtcNow
            };
        }

        public async Task<ImageUploadResultDTO> SaveImageAsync(Stream imageStream, string fileName, string contentType, FileUploadOptionsDTO? options = null)
        {
            options ??= new FileUploadOptionsDTO();
            var directory = options.Directory ?? "images";
            var directoryPath = Path.Combine(_uploadPath, directory);

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            // 生成唯一文件名
            var extension = Path.GetExtension(fileName);
            var uniqueFileName = $"{Guid.NewGuid()}{extension}";
            var thumbnailFileName = $"{Path.GetFileNameWithoutExtension(uniqueFileName)}_thumb{extension}";
            var filePath = Path.Combine(directoryPath, uniqueFileName);
            var thumbnailPath = Path.Combine(directoryPath, thumbnailFileName);

            using (var image = await Image.LoadAsync(imageStream))
            {
                // 调整图片大小
                if (image.Width > options.MaxWidth || image.Height > options.MaxHeight)
                {
                    var resizeOptions = new ResizeOptions
                    {
                        Mode = ResizeMode.Max,
                        Size = new Size(options.MaxWidth, options.MaxHeight)
                    };
                    image.Mutate(x => x.Resize(resizeOptions));
                }

                // 保存原图
                await image.SaveAsync(filePath);

                // 生成缩略图
                if (options.GenerateThumbnail)
                {
                    image.Mutate(x => x.Resize(new ResizeOptions
                    {
                        Mode = ResizeMode.Max,
                        Size = new Size(300, 300)
                    }));
                    await image.SaveAsync(thumbnailPath);
                }

                return new ImageUploadResultDTO
                {
                    FileName = uniqueFileName,
                    FileUrl = GetFileUrl(uniqueFileName, directory),
                    ThumbnailUrl = GetFileUrl(thumbnailFileName, directory),
                    FileSize = new FileInfo(filePath).Length,
                    ContentType = contentType,
                    Width = image.Width,
                    Height = image.Height,
                    UploadTime = DateTime.UtcNow
                };
            }
        }

        public async Task DeleteFileAsync(string fileUrl)
        {
            var fileName = Path.GetFileName(new Uri(fileUrl).LocalPath);
            var filePath = Path.Combine(_uploadPath, fileName);

            if (File.Exists(filePath))
            {
                await Task.Run(() => File.Delete(filePath));
            }

            // 如果是图片，尝试删除缩略图
            var thumbnailFileName = $"{Path.GetFileNameWithoutExtension(fileName)}_thumb{Path.GetExtension(fileName)}";
            var thumbnailPath = Path.Combine(_uploadPath, thumbnailFileName);

            if (File.Exists(thumbnailPath))
            {
                await Task.Run(() => File.Delete(thumbnailPath));
            }
        }

        public string GetFileUrl(string fileName, string? directory = null)
        {
            directory ??= "files";
            return $"{_baseUrl}/uploads/{directory}/{fileName}";
        }
    }
} 